package com.ge.util;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class CachePool {

	private Map mPool = null; 
	
	private String strPoolName = null;
	
	private LinkedList mList = null;
	
	private int nCapacity = 0;
	
	public CachePool(String strName, int nSize) {
		mPool = new HashMap();
		mList = new LinkedList();
		nCapacity = nSize;
		
		this.strPoolName = strName;
		if (this.strPoolName == null || this.strPoolName.length() == 0) {
			return;
		}

		mPoolMap.put(this.strPoolName, this);
	}

	public CachePool(int nSize) {
		this(null, nSize);
	}
	
	public Object get(Object objKey) {
		synchronized(mPool) {
			Object objValue = mPool.get(objKey);
			if(objValue != null) {
				mList.remove(objKey);
				mList.addFirst(objKey);
			}
			return objValue;
		}
	}

	public void put(Object objKey, Object objValue) {
		synchronized(mPool) {
			if (nCapacity == 0) {
				mPool.put(objKey, objValue);
				return;
			}

			if (mPool.size() >= nCapacity) {
				Object objLast = mList.removeLast();
				mPool.remove(objLast);
			}

			mPool.put(objKey, objValue);
			mList.addFirst(objKey);
		}
	}
 
	public int getSize() {
		return mList.size();
	}

	private static Map mPoolMap = new HashMap();
	public static CachePool getCachePool(String strName) {
		return (CachePool)mPoolMap.get(strName);
	}
}
